package com.robot.base.common.api;


import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.NetworkUtils;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.robot.base.common.domain.HttpLoggingInterceptor;
import com.robot.base.configs.PrefsManager;
import com.robot.base.util.AppUtils;

import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;


/**
 * @author robot
 * @since 2020/09/11
 * RetrofitApi 创建
 */

public class GlBaseApi {
    private static final int DEFAULT_TIMEOUT = 10;

    public static final String API_SERVER_URL_DEV = "http://114.55.147.189:48080/";
    public static final String API_SERVER_URL = API_SERVER_URL_DEV;

    public static final String PIC_BASE_URL_DEV = "https://fcj.oss-accelerate.aliyuncs.com/";
    public static final String PIC_BASE_URL_FORMAL = "https://fcj.oss-cn-hangzhou.aliyuncs.com/";
    public static final String PIC_BASE_URL_360 = "https://fcj.oss-cn-hangzhou.aliyuncs.com/";
    public static final String PIC_BASE_URL_REG = "https://fcj.oss-cn-hangzhou.aliyuncs.com/";
    public static final String PIC_BASE_URL = PIC_BASE_URL_DEV;

    public static Retrofit getRetrofit() {
        Retrofit sRetrofit = new Retrofit.Builder().baseUrl(API_SERVER_URL)
                .addConverterFactory(FastJsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(getOkhttpInstance()).build();
        return sRetrofit;
    }

    public static Retrofit getRetrofit(long timeout) {
        Retrofit sRetrofit = new Retrofit.Builder().baseUrl(API_SERVER_URL)
                .addConverterFactory(FastJsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(getOkhttpInstance(timeout)).build();
        return sRetrofit;
    }

    public static OkHttpClient getOkhttpInstance(long timeout) {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
        Cache cache = new Cache(AppUtils.getApp().getCacheDir(), 10 * 1024 * 1024);

        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
//        builder.addInterceptor(httpLoggingInterceptor);
        OkHttpClient sOkHttpClient = builder.readTimeout(timeout, TimeUnit.MILLISECONDS).connectTimeout(timeout, TimeUnit.MILLISECONDS).addNetworkInterceptor(new StethoInterceptor()).cache(cache).build();

        return sOkHttpClient;
    }

    public static OkHttpClient getOkhttpInstance() {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        Cache cache = new Cache(AppUtils.getApp().getCacheDir(), 10 * 1024 * 1024);

        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        builder.addInterceptor(httpLoggingInterceptor);
        OkHttpClient sOkHttpClient = builder.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS).connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS).writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS).addNetworkInterceptor(new StethoInterceptor()).addInterceptor(chain -> {
            Request request = chain.request();
            if (!NetworkUtils.isAvailable()) {
                int maxStale = 7 * 24 * 60 * 60; // 离线时缓存保存1周
                CacheControl tempCacheControl = new CacheControl.Builder().onlyIfCached().maxStale(maxStale, TimeUnit.SECONDS).build();
                request = request.newBuilder().cacheControl(tempCacheControl).build();
            }
            return chain.proceed(request);
        }).addInterceptor(chain -> {
            if (NetworkUtils.isAvailable()) {
//                        LogUtils.d("-----------NetworkUtils.isAvailable()");
                return chain.proceed(chain.request());
            } else {
//                        LogUtils.d("-----------AppNetErrorException");
                throw new AppNetErrorException();
            }
        }).addInterceptor(chain -> {
            Request original = chain.request();
            String userToken = "";
            if (!TextUtils.isEmpty(PrefsManager.getUserLoginInfo().getAccessToken())) {
                userToken = PrefsManager.getUserLoginInfo().getAccessToken();
            }
            Request request = original;
            Request.Builder builder1 = original.newBuilder();
            if (!TextUtils.isEmpty(userToken)) {
                builder1.addHeader("Authorization", "Bearer " + userToken);
            }
            Log.d("HeadParams-----", "token:" + userToken);
            request = builder1.method(original.method(), original.body()).build();
            return chain.proceed(request);
        }).cache(cache).build();

        return sOkHttpClient;
    }

//
//    public static OkHttpClient getOkhttpInstance() {
//        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
//        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//        Cache cache = new Cache(RobotApplication.getContext().getCacheDir(), 10 * 1024 * 1024);
//
//        OkHttpClient
//                okHttpClient = new OkHttpClient.Builder().readTimeout(7000, TimeUnit.MILLISECONDS)
//                .connectTimeout(7000, TimeUnit.MILLISECONDS)
//                .addInterceptor(httpLoggingInterceptor)
//                .addInterceptor(new GzipRequestInterceptor())
//                .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
//                .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
//                .addNetworkInterceptor(new StethoInterceptor())
//                .addInterceptor(new Interceptor() {
//                    @Override
//                    public Response intercept(Chain chain) throws IOException {
//                        Request request = chain.request();
//                        if (!NetworkUtils.isAvailable()) {
//                            int maxStale = 7 * 24 * 60 * 60; // 离线时缓存保存1周
//                            CacheControl tempCacheControl = new CacheControl.Builder().onlyIfCached().maxStale(maxStale, TimeUnit.SECONDS).build();
//                            request = request.newBuilder().cacheControl(tempCacheControl).build();
//                        }
//                        return chain.proceed(request);
//                    }
//                })
//                .cache(cache)
//                .addInterceptor(new Interceptor() {
//                    @Override
//                    public Response intercept(Chain chain) throws IOException {
//                        if (NetworkUtils.isAvailable()) {
//                            LogUtils.d("-----------NetworkUtils.isAvailable()");
//                            return chain.proceed(chain.request());
//                        } else {
//                            LogUtils.d("-----------AppNetErrorException");
//                            throw new AppNetErrorException();
//                        }
//                    }
//                })
//                .addInterceptor(new Interceptor() {
//                    @Override
//                    public Response intercept(Chain chain) throws IOException {
//                        Request original = chain.request();
////        HttpUrl url = original.url().newBuilder().addQueryParameter("deviceId", DeviceUtils.getAndroidID()).build(); //添加请求头
//                        String userToken = "";
//                        if (!TextUtils.isEmpty(PrefsManager.getUserLoginInfo().getToken())) {
//                            userToken = PrefsManager.getUserLoginInfo().getToken();
//                        }
//                        Request request = original;
//                        Request.Builder builder = original.newBuilder();
//                        if (!TextUtils.isEmpty(userToken)) {
//                            builder.addHeader("token", userToken);
//                        }
//                        builder.addHeader("version", AppUtils.getAppVersionName());
//                        Log.d("HeadParams-----","token:"+userToken);
//                        request = builder.method(original.method(), original.body()).build();
//                        return chain.proceed(request);
//                    }
//                })
//                .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
//                .build();
//        return okHttpClient;
//    }
}
